<template>
  <el-upload
    action="https://jsonplaceholder.typicode.com/posts/"
    :on-success="handleChange"
    :file-list="fileList"
    accept=".xlsx, .xls"
  >
    <el-button size="small" type="primary">上传表格</el-button>
    <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过5MB</div>
  </el-upload>
</template>
<script>
import { read, utils } from "xlsx";
export default {
  props: {
    // 表格数据
    data: {
      type: Array,
      default: () => []
    },
    // 表头
    head: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fileList: [], //上传文件列表
      tableHead: [], //表头
      tableData: [] // 表数据
    };
  },
  methods: {
    onChange(e) {
      const file = e.target.files[0];
      const fileReader = new FileReader();

      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = read(data, { type: "binary" });
          const params = [];
          // 取对应表生成json表格内容
          workbook.SheetNames.forEach(item => {
            params.push({
              name: item,
              dataList: utils.sheet_to_json(workbook.Sheets[item])
            });
            this.tableData.push(utils.sheet_to_json(workbook.Sheets[item]));
          });
          // 该算法仅针对表头无合并的情况
          if (this.tableData.length > 0) {
            // 获取excel中第一个表格数据tableData[0][0]，并且将表头提取出来
            for (const key in this.tableData[0][0]) {
              this.tableHead.push(key);
            }
          }
          return params;
          // 重写数据
        } catch (e) {
          console.log("error:" + e);
          return false;
        }
      };
      fileReader.readAsBinaryString(file);
    },
    handleChange(res, file, fileList) {
      // 将文件放入
      for (let i = 0; i < fileList.length; i++) {
        if (file.name != fileList[i].name) {
          this.fileList.push({
            name: file.name,
            url: "",
            uid: file.uid
          });
        }
      }
      const files = { 0: file };
      this.readExcel(files);
    },
    readExcel(file) {
      const fileReader = new FileReader();

      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = read(data, { type: "binary" });
          const params = [];
          // 取对应表生成json表格内容
          workbook.SheetNames.forEach(item => {
            params.push({
              name: item,
              dataList: utils.sheet_to_json(workbook.Sheets[item])
            });
            this.tableData.push(utils.sheet_to_json(workbook.Sheets[item]));
          });
          // 该算法仅针对表头无合并的情况
          if (this.tableData.length > 0) {
            // 获取excel中第一个表格数据tableData[0][0]，并且将表头提取出来
            for (const key in this.tableData[0][0]) {
              this.tableHead.push(key);
            }
          }
          return params;
          // 重写数据
        } catch (e) {
          console.log("error:" + e);
          return false;
        }
      };
      fileReader.readAsBinaryString(file[0].raw);
      console.log("导入的表格数据：", this.tableData);
      this.$emit("update:head", this.tableHead);
      this.$emit("update:data", this.tableData);
    }
  }
};
</script>
<style lang="scss" scoped>
</style>

